package com.guigu.ssyx.product.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.guigu.ssyx.product.service.FileUploadService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


@Service
public class FileUploadServiceImpl  implements FileUploadService {

    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.keyid}")
    private String keyid;
    @Value("${oss.keysecret}")
    private String keysecret;
    @Value("${oss.bucketname}")
    private String bucketName;

    @Override
    public Object fileUpload(MultipartFile file) {
        try {
            //创建实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, keyid, keysecret);

            InputStream inputStream = file.getInputStream();

            String fileName = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;

            //按照当前日期，创建文件夹，上传到文件夹中
            String timeUrl = new DateTime().toString("yyyy/MM/dd");

            fileName = timeUrl + "/" + fileName;

            ossClient.putObject(bucketName, fileName, inputStream);

            ossClient.shutdown();

            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;

            return url;
        }catch (IOException e){
            e.printStackTrace();
            return null;
        }


        //上传文件流


    }
}
